import {Spin, Space} from 'antd';
import {useEffect} from "react";
import {nanoid} from "nanoid"   // 生成唯一的ID
function gundong(props) {
    // 唯一的id
    let onlyid = nanoid()
    // 监视器
    let jianshi = null
    // 当前组件出现在可视窗口的时候，调用一次翻页函数，打开loading状态
    const huidiao = () => {
        if(!props.loading){
            props.fanye()
        }
    }
    // 组件初始化的时候创建监视器，组件销毁的时候，销毁监视器
    useEffect(() => {
        if (props.gundong) {
            jianshi = new IntersectionObserver((entries)=>{
                entries.forEach(element=>{
                    if (element.isIntersecting) {
                        // 在进入可视区域和离开可视区域时，都会触发回调
                        // isIntersecting就是进入可视区域，
                        console.log("无限滚动组件进入可视区域，触发翻页函数一次",props.loading)
                        huidiao()
                    }
                })
            })
            jianshi.observe(document.getElementById(onlyid))
        } else {
            jianshi && jianshi.disconnect()
            jianshi = null
        }

        return () => {
            jianshi && jianshi.disconnect();
            jianshi = null;
        }
    }, [props.gundong])

    if (props.gundong) {
        return (
            <div className="w-full h-10 juzhong bg-opacity-0" id={onlyid}>
                {(props.loading || null) ? <Spin size="large">正在加载</Spin> : null}
            </div>
        )
    } else {
        return (
            <div className="w-full h-10 juzhong">
                <span className="text-gray-600 select-none">全部加载完毕</span>
            </div>
        )
    }
}

export default gundong